package service

import (
	"errors"
	"ginfast/api/system/model"
	"ginfast/pkg/gmd5"
	"ginfast/pkg/orm"
	"ginfast/util"
)

const (
	defaultpwd = "123456"
)

// UserPassword 生成密码
func UserPassword(u *model.User, password string) string {
	if u.Salt == "" {
		u.Salt = util.StringRandom(6)
	}
	token := u.UserName + password + u.Salt
	return gmd5.MustEncryptString(token)
}

func UserIsExist(req *model.User) error {
	var user model.User
	db := orm.DB().Or("UserName like ?", req.UserName)
	if req.Mobile != "" {
		db = db.Or("Mobile like ?", req.Mobile)
	}
	if req.Email != "" {
		db = db.Or("Email like ?", req.Email)
	}
	return db.First(&user).Error
}

func UserCreate(u *model.User) error {
	if UserIsExist(u) == nil {
		return errors.New("user already exists")
	}
	if u.Password == "" {
		u.Password = defaultpwd
	}
	u.Password = UserPassword(u, u.Password)
	return orm.DbCreate(u)
}
